package com.atlin.project.service.fm.impl;

import cn.hutool.core.date.DateUtil;
import com.atlin.project.contant.CommonConstant;
import com.atlin.project.mapper.fm.StockIssuanceInfoMapper;
import com.atlin.project.model.dto.stockIssuanceInfo.StockIssuanceInfoQueryRequest;
import com.atlin.project.model.fm.domain.StockIssuanceInfo;
import com.atlin.project.model.vo.StockIssuanceInfoVO;
import com.atlin.project.service.fm.StockIssuanceInfoService;
import com.atlin.project.service.fm.util.LoadData;
import com.atlin.project.utils.MailUtil;
import com.atlin.project.utils.sql.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author atlin
 * @description stockIssuanceInfo 可转债相关操作实现
 * @createDate date
 */
@Slf4j
@Service
public class StockIssuanceInfoServiceImpl extends ServiceImpl<StockIssuanceInfoMapper, StockIssuanceInfo>
        implements StockIssuanceInfoService {

    @Resource
    private MailUtil mailUtil;

    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param stockIssuanceInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<StockIssuanceInfo> getQueryWrapper(StockIssuanceInfoQueryRequest stockIssuanceInfoQueryRequest) {
        QueryWrapper<StockIssuanceInfo> queryWrapper = new QueryWrapper<>();
        if (stockIssuanceInfoQueryRequest == null) {
            return queryWrapper;
        }
        Long id = stockIssuanceInfoQueryRequest.getId();
        String stockCode = stockIssuanceInfoQueryRequest.getStockCode();
        String stockName = stockIssuanceInfoQueryRequest.getStockName();
        String sortField = stockIssuanceInfoQueryRequest.getSortField();
        String sortOrder = stockIssuanceInfoQueryRequest.getSortOrder();

        queryWrapper.like(StringUtils.isNotBlank(stockCode), "stockCode", stockCode);
        queryWrapper.like(StringUtils.isNotBlank(stockName), "stockName", stockName);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public Page<StockIssuanceInfoVO> getStockIssuanceInfoVOPage(Page<StockIssuanceInfo> stockIssuanceInfoPage, HttpServletRequest request) {
        List<StockIssuanceInfo> stockIssuanceInfoList = stockIssuanceInfoPage.getRecords();
        Page<StockIssuanceInfoVO> stockIssuanceInfoVOPage = new Page<>(stockIssuanceInfoPage.getCurrent(), stockIssuanceInfoPage.getSize(), stockIssuanceInfoPage.getTotal());
        if (CollectionUtils.isEmpty(stockIssuanceInfoList)) {
            return stockIssuanceInfoVOPage;
        }
        // 填充信息
        List<StockIssuanceInfoVO> stockIssuanceInfoVOList = stockIssuanceInfoList.stream().map(StockIssuanceInfoVO::objToVo).collect(Collectors.toList());
        stockIssuanceInfoVOPage.setRecords(stockIssuanceInfoVOList);
        return stockIssuanceInfoVOPage;
    }

    /**
     * 每天8:00、18:00定时抓取数据
     */
    @Override
    @Scheduled(cron = "0 0 8,18 * * ?")
    public void dynamicLoadCbData() {
        List<StockIssuanceInfo> dataList = LoadData.loadCbData();
        int count = 0;
        for (StockIssuanceInfo stockIssuanceInfo : dataList) {
            LambdaQueryWrapper<StockIssuanceInfo> wrapper = new QueryWrapper<StockIssuanceInfo>().lambda()
                    .eq(StockIssuanceInfo::getStockCode, stockIssuanceInfo.getStockCode())
                    .eq(StockIssuanceInfo::getProgressDate, stockIssuanceInfo.getProgressDate());
            boolean exists = baseMapper.exists(wrapper);
            if (!exists) {
                boolean save = save(stockIssuanceInfo);
                if (save) count++;
            }
        }
        log.info("{}共插入{}条待发转债数据。", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), count);
    }

    /**
     * 推送当天的进展公告
     */
    @Override
    @Scheduled(cron = "0 0 9 * * ?")
    public void recommendCb() {
        QueryWrapper<StockIssuanceInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("progressDate", DateUtil.format(new Date(), "yyyy-MM-dd"));
        List<StockIssuanceInfo> list = this.list(wrapper);
        if (list.isEmpty()) {
            log.info("今日暂无数据");
            return;
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("stocks", list);
        mailUtil.sendCbMail("xiaolinjiu919@163.com", map);
    }
}




